package com.dtguai.web.web.sys.controller;

import com.dtguai.web.base.action.BaseAction;
import com.dtguai.web.common.error.ErrorCode;
import com.dtguai.web.common.validator.ValidatorUtils;
import com.dtguai.web.protocol.response.ApiResponse;
import com.dtguai.web.web.sys.form.SysLoginForm;
import com.dtguai.web.web.sys.model.SysAdminToken;
import com.dtguai.web.web.sys.model.SysDefAdmin;
import com.dtguai.web.web.sys.service.SysCaptchaService;
import com.dtguai.web.web.sys.service.SysDefAdminService;
import com.dtguai.web.web.sys.service.SysUserTokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;

/**
 * 登录相关
 *
 * @author guo
 * @date 2018年12月21日11:16:27
 */
@RestController
@RequestMapping("/web")
@Api(value = "web-登陆/登出", tags = {"web-登陆/登出"})
public class SysLoginController extends BaseAction {

    @Autowired
    private SysDefAdminService sysDefAdminService;

    @Autowired
    private SysUserTokenService sysUserTokenService;

    @Autowired
    private SysCaptchaService sysCaptchaService;

    /**
     * 登录
     */
    @ApiOperation(value = "web登陆", notes = "web登陆")
    @PostMapping(value = "/login", produces = "application/json;charset=UTF-8")
    @ApiResponses({
            @io.swagger.annotations.ApiResponse(code = 402, message = "验证码错误"),
            @io.swagger.annotations.ApiResponse(code = 412, message = "账号已被锁定,请联系管理员")
    })
    //@Sign
    //@RSADecryptBody(timeOut = 60L * 60L * 1000L)
    public ResponseEntity<ApiResponse<SysAdminToken>> login(@RequestBody SysLoginForm form) {
        if (!sysCaptchaService.validate(form.getUuid(), form.getCaptcha())) {
            return ResponseEntity.ok(new ApiResponse<>(ErrorCode.VERIFICATION_CODE_LOSE_EFFICACY));
        }
        // 表单校验
        ValidatorUtils.validateEntity(form);
        //用户信息
        SysDefAdmin admin = new SysDefAdmin();
        admin.setName(form.getName());
        List<SysDefAdmin> adminList = sysDefAdminService.selectByPage(admin, true, SysDefAdmin.class);

        //账号不存在、密码错误
        if (adminList == null || adminList.size() != 1 || !adminList.get(0).getPassword().equals(new Sha256Hash(form.getPassword(), adminList.get(0).getCode()).toHex())) {
            return ResponseEntity.ok(new ApiResponse<>(ErrorCode.NAME_PASSWORD_ERROR));
        }

        //账号锁定
        if (adminList.get(0).getStatus() == 0) {
            return ResponseEntity.ok(new ApiResponse<>(ErrorCode.ID_LOCK));
        }

        //生成token，并保存到缓存
        SysAdminToken token = sysUserTokenService.createToken(adminList.get(0).getId());
        //返回token 及 过期时间
        return ResponseEntity.ok(new ApiResponse<>(token));
    }


    /**
     * 退出
     */
    @PostMapping("/logout")
    @ApiOperation(value = "web logout", notes = "web logout")
    public ResponseEntity<ApiResponse> logout() {
        sysUserTokenService.logout(getAdminId());
        return ResponseEntity.ok(new ApiResponse());
    }

    /**
     * 验证码
     */
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //获取图片验证码
        BufferedImage image = sysCaptchaService.getCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

}
